package mysqlgo

import (
	"database/sql"
)

//ITable Table表
type ITable interface{
	Table() Table
}

//IDB DB数据库
type IDB interface {
	DBName()	string
}

//IModel Model方法
type IModel interface {
	ITable
	IDB
}

//Model 数据模型
func Model(model interface{}) *Builder {
	builder := new(Builder)
	builder.model = model
	if m, ok := builder.model.(IModel); ok {
		builder.table = m.Table()
		builder.dbAlias = m.DBName()
	} else if  m, ok := builder.model.(ITable); ok {
		builder.table = m.Table()
		builder.dbAlias = "default"
	}
	return builder
}

//QueryRow 原生查询单条数据操作
///mysqlgo.QueryRow("select * from user where username = ? and status = ?", "admin", 1)
func QueryRow(query string, args ...interface{}) (*sql.Row, error) {
	db := DB().Unsafe()
	if db == nil {
		return nil, GetError(DBNull)
	}
	return db.QueryRow(query, args), nil
}

//Query 原生查询多条数据操作
///mysqlgo.Query("select * from user where username = ? and status = ?", "admin", 1)
func Query(query string, args ...interface{}) (*sql.Rows, error){
	db := DB().Unsafe()
	if db == nil {
		return nil, GetError(DBNull)
	}
	return db.Query(query, args...)
}

//Insert 插入数据操作
///mysqlgo.Insert("insert into user(username, password) values(?,?)", "admin", "123456")
func Insert(query string, args ...interface{}) (int64, error) {
	db := DB().Unsafe()
	if db == nil {
		return -1, GetError(DBNull)
	}
	result, err := db.Exec(query, args...)
	if err != nil {
		return -1, err
	}

	return result.LastInsertId()
}

//InsertAll 插入多条数据
func InsertAll(query string, datas ...[]interface{}) error{
	db := DB().Unsafe()
	if db == nil {
		return GetError(DBNull)
	}
	tx := db.MustBegin()
	for _, data := range datas {
		_, err := db.Exec(query, data...)
		if err != nil {
			tx.Rollback()
			return err
		}
	}
	return tx.Commit()
}

//Update 更新数据操作
///mysqlgo.Update("update user set status = ?, password = ? where username = ?",1 , "test", "admin")
func Update(query string, args ...interface{}) (int64, error){
	db := DB().Unsafe()
	if db == nil {
		return -1, GetError(DBNull)
	}
	result, err := db.Exec(query, args...)
	if err != nil {
		return -1, err
	}

	return result.RowsAffected()
}

//Delete 删除操作
///mysqlgo.Delete("delete from user where username = ?", "admin")
func Delete(query string, args ...interface{}) (int64, error) {
	db := DB().Unsafe()
	if db == nil {
		return -1, GetError(DBNull)
	}
	result, err := db.Exec(query, args...)
	if err != nil {
		return -1, err
	}

	return result.RowsAffected()
}

//Exec 执行SQL语句
func Exec(query string, args ...interface{}) (sql.Result, error) {
	db := DB().Unsafe()
	if db == nil {
		return nil, GetError(DBNull)
	}

	return db.Exec(query, args...)
}
